package com.itqf.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @Description: mybatis工具类
 * 1)工厂一个应用一个对象    static{ }
 * 2) 为每个线程创建一个属于该线程的sqlSession  ThreadLocal
 *
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/11/5
 * @Time: 上午10:43
 */
public class MybatisUtils {
    //
    static SqlSessionFactory sqlSessionFactory;
    //保证每个线程都有自己的SqlSession
    static ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();

    static{
        try {
            InputStream is = Resources.getResourceAsStream("mybatisConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static  SqlSession openSession(){
       SqlSession sqlSession =  local.get();
       if (sqlSession==null){
           sqlSession = sqlSessionFactory.openSession();
           local.set(sqlSession);
       }
        return  sqlSession;
    }

    public static void  commit(){
        SqlSession sqlSession =  openSession();
        sqlSession.commit();
    }

    public static void  close(){
        SqlSession sqlSession =  openSession();
        sqlSession.close();
        local.remove();//移除sqlSession
    }

    public static void  rollback(){
        SqlSession sqlSession =  openSession();
        sqlSession.rollback();
    }

    //得到mapper
    public static <T extends Object> T getMapper(Class<T> tClass){
        return  openSession().getMapper(tClass);
    }

}
